<template>
	<el-form ref="formRef" :model="formData" :rules="formRules" label-width="10em">
		<el-form-item label="分类名称" prop="name">
			<el-input v-model="formData.name" placeholder="请输入分类名称" type="text" clearable></el-input>
		</el-form-item>
		<el-row type="flex" justify="center">
			<el-button type="primary" icon="el-icon-check" @click="onConfirm">完成{{ current + 1 }}/{{ selection.length }}
			</el-button>
			<el-button type="default" icon="el-icon-close" @click="onCancel">取消</el-button>
		</el-row>
	</el-form>
</template>

<script>
import {
	post, get
} from "@/assets/js/http.js";

export default {
	name: "banner-cate-edit",
	props: {
		selection: {
			type: Array,
			default: () => []
		}
	},
	watch: {
		selection() {
			this.setFormData();
		}
	},
	data() {
		return {
			current: 0,
			props: {
				label: "name",
				value: "id",
				children: "children",
				checkStrictly: true
			},
			formData: {
				name: "",
			},
			formRules: {
				name: [{
					required: true,
					message: "此项为必填项"
				}],
			}
		};
	},
	mounted() {
		this.setFormData();
	},
	methods: {
		setFormData() {
			const data = this.selection[this.current];
			this.formData.id = data.id;
			this.formData.name = data.name;
		},
		onConfirm() {
			this.$refs.formRef.validate(async isValid => {
				if (isValid) {
					const formData = JSON.parse(JSON.stringify(this.formData));
					await post({
						url: "/admin/basic.Village/editCate",
						data: formData,
						loading: true,
						successTip: true
					});
					if (this.current === this.selection.length - 1) {
						this.$emit("update");
						this.$parent.$emit("update:visible", false);
						this.$refs.formRef.resetFields();
					} else {
						this.current += 1;
						this.setFormData();
					}
				}
			});
		},
		onCancel() {
			if (this.current > 0) {
				this.$emit("update");
			}
			this.$parent.$emit("update:visible", false);
			this.$refs.formRef.resetFields();
		}
	}
};
</script>
